package com.gitee.poi.plugin.core.handler.data;

import com.gitee.poi.plugin.model.CellModel;
import com.gitee.poi.plugin.model.FieldStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.Collection;
import java.util.List;

/**
 * @author wangxin
 * @time 2018/10/26 17:06
 */
public class SingleListTransform implements HandlerData {

    private void prepareCell(CellModel cellModel) {
        Collection collection = (Collection) cellModel.getValue();
        int size = collection.size();
        int currentRowIndex = cellModel.getCurrentRowIndex();
        List<FieldStyle> fields = cellModel.getFields();
        int columnSize = fields.size();
        Sheet sheet = cellModel.getSheet();
        int position = cellModel.getCurrentCellIndex();
        for (int i = position + 1; i < fields.size(); i++) {
            sheet.getRow(currentRowIndex).createCell(i);
        }
        for (int rowIndex = 1; rowIndex < size; rowIndex++) {
            Row row = sheet.createRow(currentRowIndex + rowIndex);
            for (int columnIndex = 0; columnIndex < columnSize; columnIndex++) {
                row.createCell(columnIndex);
            }

        }
        for (int i = 0; i < columnSize; i++) {
            if (i != cellModel.getCurrentCellIndex()) {
                sheet.addMergedRegion(new CellRangeAddress(currentRowIndex, currentRowIndex + size - 1, i, i));
            }
        }


    }

    @Override
    public CellModel process(CellModel cellModel) {
        Collection<?> collection = (Collection) cellModel.getValue();
        int size = collection.size();
        int currentRowIndex = cellModel.getCurrentRowIndex();
        Sheet sheet = cellModel.getSheet();
        if (size > 1) {
            prepareCell(cellModel);
            int columnIndex = 0;
            for (Object obj : collection) {
                Row row = sheet.getRow(currentRowIndex + columnIndex);
                Cell cell = row.getCell(cellModel.getCurrentCellIndex());
                cell.setCellStyle(cellModel.getCellStyle());
                cellModel.getWriteCellValue().setCellValue(cell,obj);
                columnIndex += 1;
            }
            cellModel.setCurrentRowIndex(currentRowIndex + size - 1);
            cellModel.setValue(AbstractDataProcessor.NONE_PROCESS);
        } else if (size == 1) {
            Object obj = collection.iterator().next();
            cellModel.setValue(obj.toString());
        } else {
            cellModel.setValue(AbstractDataProcessor.NONE_PROCESS);
        }
        return cellModel;
    }
}
